package com.mitac.mcd.cs.mobiletracking.messageserver.util;

import java.beans.PropertyVetoException;
import java.io.PrintStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.mitac.mcd.cs.mobiletracking.messageserver.MobileServer;



public class BusinessUtil
{
	public static Log sLogger = LogFactory.getLog("system");
	public static Log aLogger = LogFactory.getLog("application"); 
	
    
    
	/**
     * 获取传递日期所在周的周一
     * @param date
     */
    public static void getFirstDayOfWeek(Calendar date){
    	int day_of_week = date.get(Calendar.DAY_OF_WEEK);
    	if(day_of_week!=1){
    		day_of_week = day_of_week -2;
    	}else{
    		day_of_week = 6;
    	}
    	date.add(Calendar.DATE, -day_of_week);
    }
    
    /**
     * 获取传递日期所在周的周日
     * @param date
     */
    public static void getLastDayOfWeek(Calendar date){
		int day_of_week = date.get(Calendar.DAY_OF_WEEK);
		if(day_of_week!=1){
			day_of_week = date.get(Calendar.DAY_OF_WEEK) - 2;
			date.add(Calendar.DATE, -day_of_week);
			date.add(Calendar.DATE, 6);
		}
    }
    
    /**
     * 获取传递日期所在月的第一天
     * @param date
     */
    public static Date getFirstDayOfMonth(Date date){
    	Calendar calendar = new GregorianCalendar();
    	calendar.setTime(date);
    	calendar.set(Calendar.DATE,calendar.getActualMinimum(Calendar.DATE));
    	return calendar.getTime();
    }
    
    /**
     * 获取传递日期所在月的最后一天
     * @param date
     */
    public static Date getLastDayOfMonth(Date date){
    	Calendar calendar = new GregorianCalendar();
    	calendar.setTime(date);
    	calendar.set(Calendar.DATE,calendar.getActualMaximum(Calendar.DATE));
    	return calendar.getTime();
    }
    
    /**
     * 检查传入的ip地址是否是被系统允许的合法的地址
     * @param ipAddress
     * @return
     */
    public static boolean checkAcceptableIpAddress(String ipAddress){
    	boolean flag = false;
    	for (NotificationAcceptableIpaddress bean:MobileServer.ipaddress){
    		if (bean.getIpAddress().equals(ipAddress)){
    			flag = true;
    		}
    	}
    	return flag;
    }
    
    /**
     * 将制定的参数通过指定的PrintStream对象发生给client端
     * @param cmd
     * @param ip
     * @param port
     * @param status
     * @param errorCode
     * @param PS
     */
    public static void sendMessage(String cmd,int status,String errorCode,PrintStream PS){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("cmd", cmd);
        map.put("status", status);
        map.put("error", errorCode);
        JSONObject json = JSONObject.fromObject(map);
        BusinessUtil.aLogger.info("开始返回json格式信息到client端..."+json.toString());
        PS.println(json.toString());
        PS.flush();
        BusinessUtil.aLogger.info("完成返回json格式信息到client端..."+json.toString());
    }
    
    /**
     * 判断字符串中cmd是属于那种类型，并返回该类型的枚举
     * @param s
     * @return
     */
    public static ClientCMDEnum.CMD judge(JSONObject jsonObject){

        ClientCMDEnum.CMD flag = null;
        try {
            if (jsonObject.get("cmd").equals("notificationcmd")){
                flag = ClientCMDEnum.CMD.notificationcmd;
            }
            if (jsonObject.get("cmd").equals("groupupdatecmd")){
                flag = ClientCMDEnum.CMD.groupupdatecmd;
            }
            if (jsonObject.get("cmd").equals("killcmd")){
                flag = ClientCMDEnum.CMD.killcmd;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
    
    /**
     * 记录异常信息到DB当中
     * @param uid
     * @param user_id
     * @param device_type
     * @param client_address
     * @param exception_prop_code
     * @param note
     */
    public static void logException(String uid,int user_id,int device_type,String client_address,String exception_prop_code,String note){
    	if (null==exception_prop_code||exception_prop_code.equals("")){
    		BusinessUtil.aLogger.info("exception_prop_code为空，不能记录异常信息...");
            return;
        }
    	java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	
        String sqlA = " insert into EXCEPTION_LOG " +
        		"(UUID,USER_ID,DEVICE_TYPE,EXCEPTION_PROP_CODE,CLIENT_IPADDRESS,RECORD_TIME,NOTE) values " +
        		"(?,?,?,?,?,?,?) ";
        try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			pst.setString(1, uid);
			pst.setInt(2, user_id);
			pst.setInt(3, device_type);
			pst.setString(4, exception_prop_code);
			pst.setString(5, client_address);
			Date date = new Date();
			pst.setTimestamp(6, new java.sql.Timestamp(date.getTime()));
			pst.setString(7, note);
			pst.executeUpdate();
			
			dbc.close();
            pst.close();
		} catch (SQLException e) {
			BusinessUtil.aLogger.error("logException:"+e);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
		
    }
    
    /**
     * log notification info to db
     * @param ID
     * @param isValidate
     * @param ipAddress
     * @param clientCount
     * @param note
     */
    public static void logNotification(String ID,int type,int clientCount,String note,boolean newest){
    	java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
    	
        String sqlA = " insert into NOTIFICATION_MSG_LOG " +
        		"(NOTIFICATION_ID,CLIENT_COUNT,LOG_TIME,NOTE,NEWEST,TYPE) values " +
        		"(?,?,?,?,?,?) ";
        try {
            dbc = DBConnection.getConnection("gpsdata");
			pst = dbc.prepareStatement(sqlA);
			pst.setString(1, ID);
			pst.setInt(2,clientCount);
			Date date = new Date();
			pst.setTimestamp(3, new java.sql.Timestamp(date.getTime()));
			pst.setString(4, note);
			pst.setBoolean(5, newest);
			pst.setInt(6, type);
			pst.executeUpdate();
			
			dbc.close();
            pst.close();
		} catch (SQLException e) {
			BusinessUtil.aLogger.error("logNotification:"+e);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
    }
    
    /**
     * log notification detail info to db
     * @param ID
     * @param uuid
     * @param failCode
     * @param resendTime
     * @param note
     */
    public static void logNotificationDetail(String ID,String uuid,String note){
    	java.sql.Connection dbc=null;
    	PreparedStatement pst = null;
        String sql = " insert into NOTIFICATION_MSG_DETAIL " +
		"(NOTIFICATION_ID,UUID,LOG_TIME,NOTE) values " +
		"(?,?,?,?) ";
        try {
            dbc = DBConnection.getConnection("gpsdata");
            	pst = dbc.prepareStatement(sql);
    			pst.setString(1, ID);
    			pst.setString(2, uuid);
    			Date date = new Date();
    			pst.setTimestamp(3, new java.sql.Timestamp(date.getTime()));
    			pst.setString(4, note);
			
			pst.executeUpdate();
			dbc.close();
            pst.close();
		} catch (SQLException e) {
			BusinessUtil.aLogger.error("logNotificationDetail:"+e);
		} catch (PropertyVetoException e) {
			e.printStackTrace();
		}
    }
    
    public static void main(String args[]) throws InterruptedException, InstantiationException, IllegalAccessException{
    	Calendar date = Calendar.getInstance();
    	System.out.println(date.get(Calendar.DAY_OF_MONTH));
    }
}
